// 测试 控制器模块
let { insertMany, count, getList, findOne, findAll } = require('../model/goods');

// 批量写入
let insertManyCofn = async (req, res) => {
  // 读取 db/goods.json
  let dataStr = require('fs').readFileSync('./db/goods.json', 'utf-8');
  let dataArr = JSON.parse(dataStr, (k, v) => {
    if (k == 'sale_type') return v.slice(0, - 2) - 0
    if (k != 'is_select' && k != 'cart_number') return v;
  })
  let r = await insertMany(dataArr);
  if (r.status === 0) return res.send({ code: 0, message: '批量写入失败', info: r.message });
  res.send({ code: 1, message: '批量写入成功' })
}

// 商品列表控制器
let listCofn = async (req, res) => {
  let { current, pagesize, search, filter, saleType, sortType, sortMethod, category } = req.query;
  // 设置默认值
  current = current ?? 1; // 默认第一页
  pagesize = pagesize ?? 12; // 默认一页12条

  sortType = sortType ?? 'goods_id';
  if (sortType == 'id') sortType = 'goods_id';
  if (sortType == 'sale') sortType = 'sale_type';
  if (sortType == 'price') sortType = 'current_price';
  sortMethod = sortMethod ?? 'ASC';

  // 排序条件
  let sort = {};
  sort[sortType] = sortMethod == 'ASC' ? 1 : -1

  // 模糊查询正则
  let searReg = new RegExp(search, 'i');
  // 查询条件--->组装
  let cond = {};
  if (search) cond.title = searReg;
  if (category) cond.category = category;
  if (filter) {
    filter == 'hot' ? cond.is_hot = 1 : ''
    filter == 'sale' ? cond.is_sale = 1 : ''
  };
  if (saleType!=10 && saleType) cond.sale_type = saleType;
  let r = await getList(cond, sort, current, pagesize);
  if (r.status === 0) return res.send({ code: 0, message: '获取失败' });

  // 统计总数据条数
  let total = await count(cond);  
  let totalPage = Math.ceil(total / pagesize);

  // totalPage
  res.send({ code: 1, message: '获取成功', list: r, totalPage });
}

let detailCofn = async (req, res) => {
  let { id } = req.query;
  let r = await findOne(id);
  if (r.status === 0) return res.send({ code: 0, message: '获取详情失败' })
  res.send({ code: 1, message: '获取详情成功', info: r[0] });
}

let catesCofn = async (req, res) => {
  let r = await findAll();

  let s = r.reduce((prev, item) => prev.add(item.category), new Set())
  res.send({ code: 1, message: '获取成功', cates: [...s] })
}


// 导出
module.exports = {
  insertManyCofn, listCofn, detailCofn, catesCofn
}